package com.example.demo;

import com.example.demo.config.DataSourceConfig;
import com.example.demo.dto.SyncSqlDto;
import com.example.demo.util.DBConnectUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * ClassName:PermentJdbc
 * Package:com.example.demo
 * TODO:
 *
 * @date:2021/8/26 17:32
 * @author:Vicky(陈烟星)
 */
@Component
public class PrepareJdbc {

    private static Logger logger = LoggerFactory.getLogger(PrepareJdbc.class);


    @Autowired
    private DataSourceConfig dataSourceConfig;


    public boolean submitPrepareJdbc(SyncSqlDto syncSqlDto) throws SQLException {
        if (syncSqlDto == null) {
            return false;
        }
        String syncSql = syncSqlDto.getSyncSql();
        String tgtTableName = syncSqlDto.getTgtTableName();
        if (StringUtils.isBlank(syncSql)) {
            return false;
        }

//        logger.info("线程id:{}处理请求,执行sql:{}", Thread.currentThread().getId(), syncSql);

        Connection connection = null;
        Statement statement = null;
        try {
            connection = dataSourceConfig.buildConnection();

            statement = connection.createStatement();

            if (StringUtils.isNotBlank(tgtTableName)) {

                statement.addBatch("delete from " + tgtTableName);
            }
            statement.addBatch(syncSql);

            int[] executeBatch = statement.executeBatch();

            boolean executeResult = executeBatch.length > 0;

            logger.info("执行结果:{}", executeResult);

            DBConnectUtil.commit(connection);
            return executeResult;
        } catch (SQLException e) {
            logger.info("执行异常:{}，srcTableName：{},tgtTableName:{}", e.getMessage(),syncSqlDto.getSrcTableName(),tgtTableName);
            // 若事务发生异常，回滚事务
            DBConnectUtil.rollback(connection);
        } finally {
            if (statement != null) {
                statement.clearBatch();
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
        return false;
    }
}
